package register

import (
	"api/config"
	"api/config/code"
	"api/libs/api"
	"api/libs/errs"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/dreamwood/ez"
	"io"
	"net/http"
	"os"
)

func RegService() {

	heartBeatUrl := fmt.Sprintf("http://%s/_reg_service", config.GetService().Register.Host)

	conf := config.GetService()
	conf.RunPath = os.Args[0]
	conf.Host = config.GetCore().ServerHost
	conf.Port = fmt.Sprintf("%d", config.GetCore().ServerPort)
	conf.Pid = os.Getpid()

	data, e := json.Marshal(conf)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	bf := bytes.NewBuffer(data)

	resp, e := http.Post(heartBeatUrl, "application/json", bf)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	body, e := io.ReadAll(resp.Body)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	message := new(api.JsonOut)
	e = json.Unmarshal(body, message)
	if errs.Try(e) {
		return
	}
	if message.Code != code.Success {
		ez.PrintError(errors.New(message.Message))
	} else {
		ez.PrintSuccess(message.Message)
	}
}

func CollectAppInfo() {
	appPath := os.Args[0]
	appPath = ez.CleanPath(appPath)
	ez.Debug(appPath)
}

func HeartBeat() {
	heartBeatUrl := fmt.Sprintf("http://%s/_heart_beat", config.GetService().Register.Host)

	conf := config.GetService()
	conf.RunPath = os.Args[0]
	conf.Host = config.GetCore().ServerHost
	conf.Port = fmt.Sprintf("%d", config.GetCore().ServerPort)
	conf.Pid = os.Getpid()

	data, e := json.Marshal(conf)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	bf := bytes.NewBuffer(data)

	resp, e := http.Post(heartBeatUrl, "application/json", bf)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	body, e := io.ReadAll(resp.Body)
	if errs.Try(e) {
		errs.Get(e)
		return
	}
	message := new(api.JsonOut)
	e = json.Unmarshal(body, message)
	if errs.Try(e) {
		return
	}
	if message.Code != code.Success {
		ez.PrintError(errors.New(message.Message))
	} else {
		ez.PrintSuccess(message.Message)
	}
}
